layui.define(['jquery', 'axios', 'base64', 'notice'], function (exports) {
    var $ = layui.jquery,
        base64 = layui.base64,
        notice = layui.notice;

    //操作成功
    const onAxiosSuccess = function (ret, success) {
        var data = typeof ret.data !== 'undefined' ? ret.data : null;
        var msg = typeof ret.msg !== 'undefined' ? ret.msg : '';
        if (typeof success === 'function') {
            var result = success.call(this, data, ret);
            if (result === false) {
                return false;
            }
        }
        if (msg != '') {
            notice.success(msg);
        }
    };
    //操作失败
    const onAxiosError = function (ret, error) {
        var data = typeof ret.data !== 'undefined' ? ret.data : null;
        var msg = typeof ret.msg !== 'undefined' ? ret.msg : '未知异常';
        if (typeof success === 'function') {
            var result = error.call(this, data, ret);
            if (result === false) {
                return false;
            }
        }
        if (msg != '') {
            notice.error(msg);
        }
    };
    //请求处理
    const onAxiosResponse = function (response) {
        try {
            response = typeof response === 'object' ? response : JSON.parse(response);
            if (!response.hasOwnProperty('data')) {
                var ret = {};
                $.extend(ret, {code: -2, msg: response, data: null});
            } else {
                var ret = response.data;
            }
        } catch (e) {
            var ret = {code: -1, msg: e.message, data: null};
        }
        //
        if ($(".layui-captcha").length > 0) {
            $(".layui-captcha").trigger('click');
        }
        return ret;
    }

    /**
     *
     * @param options
     * @param success
     * @param error
     * @returns {Promise<unknown>}
     */
    const request = function (options, success, error) {
        //允许跨域
        axios.defaults.crossDomain = true;
        // `withCredentials` 表示跨域请求时是否需要使用凭证
        axios.defaults.withCredentials = true;
        //异步请求标识
        axios.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
        axios.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest';
        //拦截器
        axios.interceptors.request.use(function (config) {
            if (config.method === 'get') {
                config.params = config.data
            }
            if (typeof ($('meta[name="X-CSRF-TOKEN"]').attr('content')) != 'undefined') {
                config.headers = {
                    "X-CSRF-TOKEN": $('meta[name="X-CSRF-TOKEN"]').attr('content')
                }
            }
            return config;
        })

        /*  axios($.extend({
              method: "get"
              , responseType: 'json'
              , timeout: 60000
          }, options)).then(function (response) {
              var ret = onAxiosResponse(response);
              if (ret.code === 1) {
                  onAxiosSuccess(ret, success);
              } else {
                  onAxiosError(ret, error);
              }
          }).catch(function (response) {
              var ret = onAxiosResponse(response);
              onAxiosError(ret, error);
          });
  */
        axios($.extend({
            method: "get"
            , responseType: 'json'
            , timeout: 60000
        }, options)).then(function (response) {
            var ret = onAxiosResponse(response);
            if (ret.code === 0) {
                onAxiosError(ret, error);
            } else {
                onAxiosSuccess(ret, success)
            }
        }).catch(function (response) {
            var ret = onAxiosResponse(response);
            onAxiosError(ret, error);
        });


        /*  return new Promise((resolve, reject) => {
              axios($.extend({
                  method: "get"
                  , responseType: 'json'
                  , timeout: 60000
              }, options)).then((res) => {
                  if (res.data.code === 0) {
                      resolve(res.data)
                  } else {
                      reject(res.data)
                  }
              }).catch((error) => {
                  reject(error)
              })
          })*/
    }

    /**
     * 实例化请求参数
     * @param data
     * @returns {string}
     */
    const stringify = function (data) {
        return Object.keys(data).sort().map(key => key + '=' + data[key]).join('&')
    }

    /* const form_info = function (form) {
         var method = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
         method = method && (method === 'GET' || method === 'POST') ? method : 'GET';
         var url = form.attr("action");
         url = url ? url : location.href;
         var loading = form.attr('data-loading');
         loading = typeof loading == 'undefind' ? null : loading;
         //修复当存在多选项元素时提交的BUG
         var params = {};
         var multipleList = $("[name$='[]']", form);
         if (multipleList.length > 0) {
             var postFields = form.serializeArray().map(function (obj) {
                 return $(obj).prop("name");
             });
             $.each(multipleList, function (i, j) {
                 if (postFields.indexOf($(this).prop("name")) < 0) {
                     params[$(this).prop("name")] = '';
                 }
             });
         }
         var data = form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '');
         var form_info = {}
         form_info.method = method;
         form_info.url = url;
         form_info.loading = loading;
         form_info.data = data;
         form_info.test = base64.encode(data);
         return form_info;
     }*/
    exports('my_form',
        {
            request: request,
            stringify: stringify,
        }
    );

})
